-- ======================================================================
-- Hell Logic Sniffer Addon 
-- 
-- Copyright 2013 Hell-Prototypes
--
-- http://www.hellprototypes.com/
-- ======================================================================

ModuleClass = "LS_PLUGIN"
ModuleName  = "Decoded Data Split"
ModuleTip   = "Split decoded data by assigned minimum spacing time"

VAR_MINI_TIME = "Decoded_Data_Split_MIN_TIME"

function time_consuming(start_, end_)
	local ns = (end_ - start_) * g_sampling_period
	local us = ns/1000
	local ms = us/1000
	
	return ns, us, ms
end

function get_current_channel()
	local param = LS_API.GetCommonParameter()
	if #param < 4 then
		return -1
	end

	return param[4]
end

function get_minimum_time()
	local last = LS_API.ReadVariable(VAR_MINI_TIME)
	if not last then last = 1000 end

	local mini_time = LS_API.InputBox(last, "Input minimum spacing time (Unit: uS)")
    if mini_time == nil then
		return nil
    end

	if last ~= mini_time then
		LS_API.SaveVariable(VAR_MINI_TIME, mini_time)
	end

	return mini_time
end

function main ()
	local current_channel = get_current_channel()
	local Decoded_Data = LS_API.GetChannelDecodedData(current_channel)

    if type(Decoded_Data) ~= "table" then
		LS_API.MessageBox("No decoded data found in channel : " .. current_channel)
		return
	end
	if #Decoded_Data < 4 then
		LS_API.MessageBox("No work to do, Data Length:" .. #Decoded_Data)
		return
	end
	
	local spacing_time_us = get_minimum_time() --us
	if spacing_time_us == nil then
		return
	end
	local param = LS_API.GetCommonParameter()
	if #param < 4 then
		LS_API.MessageBox("Error param : table size : " .. #param)
		return
	end
	local spacing_bits = spacing_time_us * 1000 / param[1]

    LS_API.ReportPushBack("========================================================")
    LS_API.ReportPushBack("Decoded Data Split, Decode data length : " .. #Decoded_Data/2)
	LS_API.ReportPushBack("========================================================\r\n")
	
	local ns, us, ms, time
	local index = 3
	local last_bit_index = Decoded_Data[1]
	local element = Decoded_Data[2] .. " "
    while index < #Decoded_Data do
		local bit_index = Decoded_Data[index]
		index = index + 1
		if (bit_index - last_bit_index) > spacing_bits then
			LS_API.ReportPushBack(element)
			element = ""
			ns, us, ms = time_consuming(last_bit_index, bit_index)
			time = string.format("\r\nSpace: %.3fms\r\n", ms)
			LS_API.ReportPushBack(time)
		end
		element = element .. Decoded_Data[index] .. " "
		index = index + 1
		last_bit_index = bit_index
	end
	LS_API.ReportPushBack(element)
end
